package cn.edu.stu.syllabus.main;

import javax.inject.Inject;

import cn.edu.stu.syllabus.repository.banner.local.BannerInfoEntry;
import cn.edu.stu.syllabus.repository.banner.BannerRepository;
import cn.edu.stu.syllabus.utils.RxSchedulerUtils;
import rx.Subscriber;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

import static cn.edu.stu.syllabus.utils.NullPointerUtils.checkNotNull;

/**
 * Created by daidaijie on 2017/3/11.
 */

public class MainPresenter implements MainContract.Presenter {

    private final MainContract.View mView;

    private final BannerRepository mBannerRepository;

    private CompositeSubscription mSubscriptions;

    @Inject
    public MainPresenter(MainContract.View view, BannerRepository bannerRepository) {
        mView = checkNotNull(view);
        mBannerRepository = checkNotNull(bannerRepository);
        mSubscriptions = new CompositeSubscription();

    }

    @Inject
    public void setupListeners() {
        mView.setPresenter(this);
    }

    @Override
    public void subscribe() {
        loadBanner();
    }

    private void loadBanner() {
        Subscription subscription = mBannerRepository.getBannerInfos()
                .compose(RxSchedulerUtils.<BannerInfoEntry>io2mainSchedulersTransformer())
                .subscribe(new Subscriber<BannerInfoEntry>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(BannerInfoEntry bannerInfoEntry) {
                        if (mView.isActive() && bannerInfoEntry != null) {
                            mView.setBannerPage(bannerInfoEntry.getBannerEntries());
                        }
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public void unsubscribe() {
        mSubscriptions.unsubscribe();
    }
}
